<!-- eslint-disable @typescript-eslint/no-explicit-any -->
<script setup lang="ts">
  import { inject, onMounted, ref } from 'vue'
  import SvgIcon from '@/components/SvgIcon/index.vue'
  import { NTooltip, NEllipsis, useMessage, NSpin } from 'naive-ui'
  import CreateLibModal from './CreateLibModal.vue'
  import { deleteSchemeLibrary, exportScheme, getSchemeLibList } from '@/api/scheme'
  import type { Scheme } from '../types'
  import DeleteModal from '@/components/common/DeleteModal/index.vue'
  import { useRouter } from 'vue-router'
  const router = useRouter()
  const getList = async () => {
    const res = await getSchemeLibList()
    libs.value = res
  }
  const message = useMessage()
  const libs = ref<Scheme[]>([])
  const handleCreateLibrary = () => {
    createLibModalRef.value.handleOpen()
  }

  const handleAuditLibrary = () => {
    console.log('待我审核 - 方案生成页面')
    // 在这里添加方案生成页面特有的逻辑
  }

  const handleClick = async (lib: any) => {
    await router.push(`/createScheme/${lib.id}`)
  }

  const createLibModalRef = ref()
  const deleteModalRef = ref()
  const deleteId = ref<string | number>()
  const beforeHandleDelete = async ({ id, name }: { id: string | number; name: string }) => {
    deleteId.value = id
    deleteModalRef.value.showModal(`确定要删除方案库“${name}”吗？`)
  }

  const handleDelete = async () => {
    if (!deleteId.value) return
    const data = await deleteSchemeLibrary({ id: deleteId.value })
    if (+data === 0) {
      message.error(`该方案库下存在方案，不可删除`)
      return
    }
    await getList()
    deleteId.value = undefined
  }

  const exportLoading = ref(false)
  const handleExport = async (lib: any) => {
    exportLoading.value = true
    const res = await exportScheme({ id: lib.id }).finally(() => {
      exportLoading.value = false
    })
    // blob转出文件是zip文件, 名字为lib.name.zip
    const blob = new Blob([res], { type: 'application/zip' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${lib.name}.zip`
    a.click()
  }

  const createSuccess = async (name: string) => {
    message.success(`${name}创建成功`)
    await getList()
  }

  // 注入父组件提供的方法注册函数
  const registerSchemeMethods = inject('registerSchemeMethods') as
    | ((methods: { handleCreateLibrary?: () => void; handleAuditLibrary?: () => void }) => void)
    | undefined

  onMounted(async () => {
    // 注册方法给父组件
    if (registerSchemeMethods) {
      registerSchemeMethods({
        handleCreateLibrary,
        handleAuditLibrary,
      })
    }
    await getList()
  })
</script>

<template>
  <n-spin :show="exportLoading" class="h-full" description="方案库导出中...">
    <div class="h-full bg-white rounded p-5">
      <!-- grid布局，每行布局4个， gap是20px -->
      <div class="grid grid-cols-4 gap-5 pingfang">
        <div
          v-for="lib in libs"
          :key="lib.id"
          @click="handleClick(lib)"
          class="bg-[#F2F6FA] rounded py-3 px-4 h-[190px] flex flex-col justify-between cursor-pointer"
        >
          <div class="flex justify-between gap-4">
            <div class="h-full flex items-center justify-center w-[72px]">
              <SvgIcon class="text-[48px]" name="library" />
            </div>
            <div class="flex-1">
              <div class="text-[16px] font-bold mt-3 h-9 leading-9">{{ lib.name }}</div>
              <n-ellipsis :line-clamp="2" class="text-[14px] text-[#666D7A] mt-2">{{
                lib.description
              }}</n-ellipsis>
              <div class="text-[12px] text-[#4A5055] mt-[6px]">{{ lib.createTime }}</div>
            </div>
          </div>
          <div class="flex justify-between items-center">
            <div class="flex gap-2">
              <div
                v-for="category in lib.schemeCategoryList"
                :key="category.id"
                class="h-7 leading-7 text-[12px] text-[#4A5055] border border-[#DDE2E9] rounded px-2"
              >
                {{ category.categoryName }}
              </div>
            </div>
            <n-tooltip placement="bottom-end" class="more-tooltip" :show-arrow="false">
              <template #trigger>
                <div class="flex items-center" @click.stop="() => {}">
                  <SvgIcon
                    class="text-[24px] text-[transparent] hover:text-white cursor-pointer"
                    name="more"
                  />
                </div>
              </template>
              <div class="cursor-pointer rounded-lg text-[#000000] pingfang text-[14px]">
                <div
                  class="h-8 leading-8 px-2 hover:bg-[#F5F5F5] flex items-center"
                  @click="handleExport(lib)"
                >
                  <SvgIcon class="text-[16px] mr-1" name="export" />
                  <span>导出</span>
                </div>
                <div
                  @click="beforeHandleDelete(lib)"
                  class="h-8 leading-8 px-2 hover:bg-[#F5F5F5] flex items-center"
                >
                  <SvgIcon class="text-[16px] mr-1" name="delete" />
                  <span>删除</span>
                </div>
              </div>
            </n-tooltip>
          </div>
        </div>
      </div>
      <CreateLibModal @create="createSuccess" ref="createLibModalRef" />
      <DeleteModal ref="deleteModalRef" @submit="handleDelete" />
    </div>
  </n-spin>
</template>

<style lang="less" scoped>
  :deep(.n-spin-content) {
    height: 100%;
  }
</style>
